package cn.fl.ref.fribaseinfo.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.hibernate.validator.internal.util.privilegedactions.SetAccessibility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.itextpdf.text.pdf.PdfStructTreeController.returnType;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.service.IPrjCstCorpTeamResumeService;
import cn.fl.ref.fribaseinfo.service.IFriBaseInfoService;
import cn.fl.ref.fribaseinfo.transform.BankAccInfoVOTransform;
import cn.fl.ref.fribaseinfo.transform.FriBaseInfoVOTransform;
import cn.fl.ref.fribaseinfo.vo.BankAccInfoVO;
import cn.fl.ref.fribaseinfo.vo.FriBaseInfoVO;
import fl.flow.facade.flow.dto.FlowStartParamsDTO;
import fl.ref.fribaseinfo.condition.BankAccInfoQueryCondition;
import fl.ref.fribaseinfo.condition.FriBaseInfoQueryCondition;
import fl.ref.fribaseinfo.constant.FriBaseInfoConstant;
import fl.ref.fribaseinfo.dto.BankAccInfoDTO;
import fl.ref.fribaseinfo.dto.FriBaseInfoDTO;
import fl.ref.fribaseinfo.service.IBankAccInfoApiService;
import fl.ref.fribaseinfo.service.IFriBaseInfoApiService;

/**
 * @Description: 融资机构基础信息
 */
@Service
public class FriBaseInfoServiceImpl implements IFriBaseInfoService {

	private static final Logger logger = LoggerFactory.getLogger(IPrjCstCorpTeamResumeService.class);

	/**
	 * 融资机构基础信息
	 */
	@Autowired
	private IFriBaseInfoApiService friBaseInfoApiService;

	/**
	 * 银行帐号信息
	 */
	@Autowired
	private IBankAccInfoApiService bankAccInfoApiService;

	/**
	 * 数据字典服务
	 */
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;

	@Override
	public FriBaseInfoVO selectById(Long id, String sysCd, String orgCd) throws BaseException {
		if (StringUtils.isEmpty(id)) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
		}
		logger.info("FriBaseInfoVO selectById Long id : " + id);
		FriBaseInfoDTO dto = this.friBaseInfoApiService.selectById(id, sysCd, orgCd);
		JSONObject jobj = JSONObject.fromObject(dto);
		FriBaseInfoVO friBaseInfoVO = FriBaseInfoVOTransform.toVO(dto);
		BankAccInfoQueryCondition bankAccInfoQC = new BankAccInfoQueryCondition();
		bankAccInfoQC.setFundRasInsId(id);
		bankAccInfoQC.setSysCd(sysCd);
		bankAccInfoQC.setOrgCd(orgCd);
		List<BankAccInfoDTO> bankAccInfoDTOs = bankAccInfoApiService.searchList(bankAccInfoQC);
		JSONArray jarray = JSONArray.fromObject(bankAccInfoDTOs);
		logger.info("FriBaseInfoVO selectById FriBaseInfoDTO : " + jobj.toString() + " ; bankAccInfoDTOs :" + jarray.toString());
		friBaseInfoVO.setBankAccInfoVOs(BankAccInfoVOTransform.toVOList(bankAccInfoDTOs));
		return friBaseInfoVO;
	}

	@Override
	public Long add(FriBaseInfoVO entity) throws BaseException {
		if (null == entity) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
		}

		Long id = friBaseInfoApiService.add(FriBaseInfoVOTransform.toDTO(entity));

		// 系统日志-有用户的情况下
		BaseLogUtils.info(logger, "add", "新增FriBaseInfo数据.", CurrentThreadContext.getCurrentUserName());

		// 系统日志-无用户的情况下
		BaseLogUtils.info(logger, "add", "新增FriBaseInfo数据.");
		return id;
	}

	@Override
	public boolean removeById(Long id) throws BaseException {
		if (StringUtils.isEmpty(id)) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
		}
		return this.friBaseInfoApiService.removeById(id);
	}

	@Override
	public boolean modify(FriBaseInfoVO entity) throws BaseException {
		if (null == entity) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
		}

		return this.friBaseInfoApiService.modify(FriBaseInfoVOTransform.toDTO(entity));
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException {
		if (null == page)
			page = new Pager();
		return this.friBaseInfoApiService.searchListPage(page);
	}

	@Override
	public List<FriBaseInfoVO> searchList(FriBaseInfoQueryCondition condition) {
		condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
		condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		return FriBaseInfoVOTransform.toVOList(this.friBaseInfoApiService.searchList(condition));
	}

	@Override
	public boolean isInsAbbExist(Long id, String insAbb) throws BaseException {
		FriBaseInfoQueryCondition condition = new FriBaseInfoQueryCondition();
		if (StringUtils.isBlank(insAbb)) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
		} else {
			condition.setInsAbb(insAbb);
			condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
			condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		}
		List<FriBaseInfoDTO> insAbbExtLists = friBaseInfoApiService.searchList(condition);
		if (insAbbExtLists.size() == 0) {
			return false;
		}
		if (insAbbExtLists.size() == 1 && null == id) {
			return true;
		}
		if (insAbbExtLists.size() == 1 && null != id) {
			if (insAbbExtLists.get(0).getId().longValue() == id.longValue()) {
				return false;
			} else {
				return true;
			}
		}
		return true;
	}

	@Override
	public boolean isAccNumExist(List<BankAccInfoVO> bankAccInfoVOs) throws BaseException {
		for (int i = 0; i < bankAccInfoVOs.size(); i++) {
			for (int j = i + 1; j < bankAccInfoVOs.size(); j++) {
				if (bankAccInfoVOs.get(i).getAccNum().equals(bankAccInfoVOs.get(j).getAccNum())) {
					return true;
				}
			}
		}
		return false;
	}

	@Override
	public List<KeyValueVO> getKvList(String grpCd) throws BaseException {
		List<KeyValueVO> kvList = new ArrayList<>();
		try {
			List<SysDictionaryDTO> sysDictionaryDTOList = this.sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(),
					CurrentThreadContext.getCurrentOrgCd(), grpCd);
			if (CollectionUtils.isNotEmpty(sysDictionaryDTOList)) {
				for (SysDictionaryDTO sysDictionaryDTO : sysDictionaryDTOList) {
					KeyValueVO keyValueVO = new KeyValueVO();
					keyValueVO.setKey(sysDictionaryDTO.getCode());
					keyValueVO.setValue(sysDictionaryDTO.getCodeNm());
					kvList.add(keyValueVO);
				}
			}
		} catch (BaseException e) {
			BaseLogUtils.info(logger, "getKvList", "获取字典项组" + grpCd + "失败.ERROR:" + e.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception e) {
			BaseLogUtils.error(logger, "getKvList", "获取字典项组" + grpCd + "失败,系统错误.ERROR:" + e.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return kvList;
	}

	@Override
	public DataResultDTO addFlowStart(FlowStartParamsDTO flowStartParamsDTO) throws BaseException {
		if (StringUtils.isEmpty(flowStartParamsDTO.getCrtUsrId()) || StringUtils.isEmpty(flowStartParamsDTO.getBusinessKey())) {
			BaseLogUtils.info(logger, "addFlowStart", "用户ID和业务数据主键必须要存在!", CurrentThreadContext.getCurrentUserName());
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "用户ID和业务数据主键必须要存在!");
		}
		return this.friBaseInfoApiService.addFlowStart(flowStartParamsDTO);
	}
	//再融资机构账户审核流程 by gengchunlan 20180706
	@Override
	public DataResultDTO addFlowStartForAccount(FlowStartParamsDTO flowStartParamsDTO) throws BaseException {
		if (StringUtils.isEmpty(flowStartParamsDTO.getCrtUsrId()) || StringUtils.isEmpty(flowStartParamsDTO.getBusinessKey())) {
			BaseLogUtils.info(logger, "addFlowStartForAccount", "用户ID和业务数据主键必须要存在!", CurrentThreadContext.getCurrentUserName());
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "用户ID和业务数据主键必须要存在!");
		}
		return this.friBaseInfoApiService.addFlowStartForAccount(flowStartParamsDTO);
	}
	@Override
	public Pager searchFlowPageById(Pager page) throws BaseException {
		if (null == page)
			page = new Pager();
		return this.friBaseInfoApiService.searchFlowPageById(page);
	}

	@Override
	public List<KeyValueVO> searchYesNoKVList() throws BaseException {
		List<KeyValueVO> kvList = new ArrayList<>();

		KeyValueVO keyValueVO1 = new KeyValueVO();
		keyValueVO1.setKey("0");
		keyValueVO1.setValue("否");
		kvList.add(keyValueVO1);

		KeyValueVO keyValueVO = new KeyValueVO();
		keyValueVO.setKey("1");
		keyValueVO.setValue("是");
		kvList.add(keyValueVO);

		return kvList;
	}
	@Override
	public Pager searchBaListPage(Pager page) throws BaseException {
		if (null == page)
			page = new Pager();
		try {
			
			Pager pager=bankAccInfoApiService.searchListPage(page);
			List<BankAccInfoDTO> list=(List<BankAccInfoDTO>)pager.getResultList();
			List<BankAccInfoVO> voList = BankAccInfoVOTransform.toVOList(list);
			pager.setResultList(voList);
			for (int i = 0; i < voList.size(); i++) {
				BankAccInfoVO vo=voList.get(i);
				
				this.setAcc(vo);
			}
			return pager;
			
		} catch (Exception e) {
			BaseLogUtils.error(logger, "searchBaListPage", "失败,系统错误.ERROR:" + e.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return null;
	}
	@Override
	public List<BankAccInfoVO> selectListForPay(BankAccInfoQueryCondition condition) throws BaseException {
		if (null == condition)
			condition = new BankAccInfoQueryCondition();
		try {
			List<BankAccInfoDTO> list=bankAccInfoApiService.selectListForPay(condition);;
			List<BankAccInfoVO> voList = BankAccInfoVOTransform.toVOList(list);
			for (int i = 0; i < voList.size(); i++) {
				BankAccInfoVO vo=voList.get(i);
				
				this.setAcc(vo);
			}
			return voList;
		} catch (Exception e) {
			BaseLogUtils.error(logger, "selectListForPay", "失败,系统错误.ERROR:" + e.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return null;
	}
	@Override
	public BankAccInfoVO selectAccById(Long id, String sysCd, String orgCd) throws BaseException {
		if (StringUtils.isEmpty(id)) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
		}
		try {
			BankAccInfoDTO bankAccInfoDTO = this.bankAccInfoApiService.selectById(id, sysCd, orgCd);
			BankAccInfoVO vo= BankAccInfoVOTransform.toVO(bankAccInfoDTO);
			this.setAcc(vo);
			return vo;
		} catch (Exception e) {
			BaseLogUtils.error(logger, "selectAccById", "失败,系统错误.ERROR:" + e.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return null;
	}
	@Override
	public Long addPayAcc(BankAccInfoVO entity) throws BaseException {
		if (null == entity) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
		}
		Long id;
		try {
			if (entity.getId()!=null) {
				id=entity.getId();
				bankAccInfoApiService.modify(BankAccInfoVOTransform.toDTO(entity));
			}else {
				entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId()); // 新增人
				entity.setCrtTm(new Date()); // 新增时间
				entity.setPayNum(new Long(1));
				id = bankAccInfoApiService.add(BankAccInfoVOTransform.toDTO(entity));
	
			}
			
			// 系统日志-有用户的情况下
			BaseLogUtils.info(logger, "add", "新增FriBaseInfo数据.", CurrentThreadContext.getCurrentUserName());
	
			// 系统日志-无用户的情况下
			BaseLogUtils.info(logger, "add", "新增FriBaseInfo数据.");
			return id;
		} catch (Exception e) {
			BaseLogUtils.error(logger, "addPayAcc", "失败,系统错误.ERROR:" + e.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return null;
	}
	@Override
	public void changeNum(String id,String num) throws BaseException {
		if (null == id) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
		}
		bankAccInfoApiService.changeNum(id,num);
		
	}
	@Override
	public List<KeyValueVO> getAccStsCd(){
		List<KeyValueVO> kvList = new ArrayList<>();

		KeyValueVO keyValueVO = new KeyValueVO();
		keyValueVO.setKey("1");
		keyValueVO.setValue(FriBaseInfoConstant.BANK_ACC_INFO_ACC_STS_CD_1);
		kvList.add(keyValueVO);

		KeyValueVO keyValueVO1 = new KeyValueVO();
		keyValueVO1.setKey("0");
		keyValueVO1.setValue(FriBaseInfoConstant.BANK_ACC_INFO_ACC_STS_CD_0);
		kvList.add(keyValueVO1);

		return kvList;
	}
	/**
	 * 设置账户
	 * @param vo
	 */
	public void setAcc(BankAccInfoVO vo){
		try{
			if ("1".equals(vo.getAccStsCd())) {//状态
				vo.setAccStsCdNm(FriBaseInfoConstant.BANK_ACC_INFO_ACC_STS_CD_1);
			}else {
				vo.setAccStsCdNm(FriBaseInfoConstant.BANK_ACC_INFO_ACC_STS_CD_0);
			}
			//账户用途
			if (!StringUtils.isBlank(vo.getAccTypCd())) {
				List<KeyValueVO> accTyp =sysDictionaryApiService.getKvList(FriBaseInfoConstant.BANK_ACC_INFO_ACC_TYP_CD,CurrentThreadContext.getCurrentSysCd(),
						CurrentThreadContext.getCurrentOrgCd());
				String[] typs=vo.getAccTypCd().split(";");
				String typnm="";
				for (int j = 0; j < accTyp.size(); j++) {
					for (int j2 = 0; j2 < typs.length; j2++) {
						if (typs[j2].equals(accTyp.get(j).getKey())) {
							typnm += accTyp.get(j).getValue()+";";
							
						}
					}
				}
				if (StringUtils.isNotBlank(typnm)) {
					typnm=typnm.substring(0, typnm.length()-1);
				}
				vo.setAccTypCdNm(typnm);
			}
			
			//可投放款项
			if (!StringUtils.isBlank(vo.getPurpCds())) {
				List<KeyValueVO> accTyp =sysDictionaryApiService.getKvList(FriBaseInfoConstant.BANK_ACC_INFO_PURP_CD,CurrentThreadContext.getCurrentSysCd(),
						CurrentThreadContext.getCurrentOrgCd());
				String[] typs=vo.getPurpCds().split(";");
				String typnm="";
				for (int j = 0; j < accTyp.size(); j++) {
					for (int j2 = 0; j2 < typs.length; j2++) {
						if (typs[j2].equals(accTyp.get(j).getKey())) {
							typnm += accTyp.get(j).getValue().replace("账号", "")+";";
						}
					}
				}
				if (StringUtils.isNotBlank(typnm)) {
					typnm=typnm.substring(0, typnm.length()-1);
				}
				vo.setPurpCdsNm(typnm);
			}
			//机构名称
			if (vo.getFundRasInsId()!=null) {
				FriBaseInfoDTO  dto=friBaseInfoApiService.selectById(vo.getFundRasInsId(), CurrentThreadContext.getCurrentSysCd(),
						CurrentThreadContext.getCurrentOrgCd());
				if(dto!=null) {
					vo.setFundRasInsIdNm(dto.getFundRasInsNm());
					vo.setBussinessLine(dto.getBussinessLine());//REQ-12803  业务线  by gengchunlan 20200723
					vo.setBussinessLineNm(dto.getBussinessLineNm());//REQ-13543  资管机构业务线修改
				}
			}
		} catch (Exception e) {
			BaseLogUtils.error(logger, "setAcc", "失败,系统错误.ERROR:" + e.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		
	}

	@Override
	public void syncBankAcc() throws BaseException {
		// TODO Auto-generated method stub
		this.bankAccInfoApiService.syncBankAcc(new Date());
	}

	@Override
	public void modifyExchangePriority(FriBaseInfoVO friBaseInfoVO, FriBaseInfoVO friBaseInfoVO2) throws BaseException {

		//1、修改当前机构资管优先级
		Integer zgNum = friBaseInfoVO.getZgNum();//当前机构资管优先级排号
		
		FriBaseInfoVO friBaseInfoVOUpdate = new FriBaseInfoVO();
		
		friBaseInfoVOUpdate.setId(friBaseInfoVO.getId());
		friBaseInfoVOUpdate.setZgNum(friBaseInfoVO2.getZgNum());
		friBaseInfoVOUpdate.setMdfTm(new Date());
		friBaseInfoVOUpdate.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
		
		this.modify(friBaseInfoVOUpdate);
		
		//2、修改上一个或下一个资管机构优先级
		FriBaseInfoVO friBaseInfoVOUpdate2 = new FriBaseInfoVO();
		
		friBaseInfoVOUpdate2.setId(friBaseInfoVO2.getId());
		friBaseInfoVOUpdate2.setZgNum(zgNum);//上一个或下一个资管机构优先级改成 当前机构资管优先级
		friBaseInfoVOUpdate2.setMdfTm(new Date());
		friBaseInfoVOUpdate2.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
		
		this.modify(friBaseInfoVOUpdate2);
	}

	@Override
	public DataResultDTO addFlowStartForGuarantee(FlowStartParamsDTO flowStartParamsDTO) {
		return friBaseInfoApiService.addFlowStartForGuarantee(flowStartParamsDTO);
	}
}
